#include <myhead.h>
#include "../common/mynet.h"
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;      
typedef struct sockaddr_un addr_un_t;

void login(int sk, msg_ret_t* msgRet);
void reg(int sk, msg_ret_t* msgRet);

//函数转移表
void (*funcArr[])(int,msg_ret_t*)={login,reg};

int main(int argc, const char *argv[])
{
	if(argc != 3){//argv[1]:服务端ip argv[2]:服务端port
		fprintf(stderr,"参数有误\n");
		return -1;
	}
	//与服务端建立连接
	//1.1 创建socket文件
	int sk=socket(AF_INET, SOCK_STREAM, 0);
	if(sk==-1){
		perror("与服务端的连接建立失败 socket error");
		return -1;
	}

	//1.2 connect
	addr_in_t addr;
	addr.sin_family=AF_INET;
	addr.sin_port=htons(atoi(argv[2]));
	addr.sin_addr.s_addr=inet_addr(argv[1]);
	socklen_t addrlen=sizeof(addr);

	if(connect(sk, (struct sockaddr*)&addr, addrlen)==-1){
		perror("connect error");
		return -1;
	}
	printf("与服务端成功建立连接\n");


	//操作界面 
	while(1){
		printf("*******************\n");
		printf("\t1-登录\n");
		printf("\t2-注册\n");
		printf("\tQ-退出\n");
		//int cmd;
		//fscanf(stdin,"%d", &cmd);
		int cmd=getchar();
		getchar();//吸回车
		//
		msg_send_t msgSend={0};
		msg_ret_t msgRet={0};
		//调用函数转移表
		printf("cmd=[%d],[%ld]\n", cmd, sizeof(funcArr)/sizeof(void*));
		if(cmd=='Q'){
			break;
		}
		if(cmd<49||cmd>49+sizeof(funcArr)/sizeof(void*)){
			printf("错误的指令！请重新输入\n");
			continue;
		}
		//调用
		funcArr[cmd-49](sk, &msgRet);
		if(msgRet.ret == 1){
			printf("操作成功\n");
			continue;
		}
		printf("操作失败！错误原因[%d][%s]\n", msgRet.ret,msgRet.errmsg);
	}	
	close(sk);
	printf("客户端已经关闭\n");
	//
	return 0;
}

void login(int sk, msg_ret_t* msgRet){
	printf("\t\t【登录】\n");
	char user[20];
	printf("\t\t用户名:");
	fgets(user,sizeof(user),stdin);
	user[strlen(user)-1]=0;

	char passwd[20];
	printf("\t\t密码:");
	fgets(passwd,sizeof(passwd),stdin);
	passwd[strlen(passwd)-1]=0;

	msg_send_t msg;
	msg_send_init(&msg, 1, user,passwd);

	ssize_t cnt=send(sk, &msg, sizeof(msg),0);
	printf("发送[%ld]个字节\n", cnt);
	if(cnt == -1){
		perror("send error");
		return;
	}

	cnt=recv(sk,msgRet,sizeof(msg_ret_t),0);
	printf("收到[%ld]个字节\n", cnt);
}

void reg(int sk, msg_ret_t* msgRet){
	printf("\t\t【注册】\n");
	char user[20];
	printf("\t\t用户名:");
	fgets(user,sizeof(user),stdin);
	user[strlen(user)-1]=0;

	char passwd[20];
	printf("\t\t密码:");
	fgets(passwd,sizeof(passwd),stdin);
	passwd[strlen(passwd)-1]=0;

	char passwd2[20];
	printf("\t\t确认密码:");
	fgets(passwd2,sizeof(passwd2),stdin);
	passwd2[strlen(passwd2)-1]=0;

	if(strcmp(passwd,passwd2)!=0){
		msgRet->ret=2;
		strcpy(msgRet->errmsg,"两次输入的密码不一致\n");
		return;
	}

	msg_send_t msg;
	msg_send_init(&msg, 2, user,passwd);

	ssize_t cnt=send(sk, &msg, sizeof(msg),0);
	printf("发送[%ld]个字节\n", cnt);
	if(cnt == -1){
		perror("send error");
		return;
	}

	cnt=recv(sk,msgRet,sizeof(msg_ret_t),0);
	printf("收到[%ld]个字节\n", cnt);
}


















